package com.erf.message;

import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.nio.charset.StandardCharsets;

/**
 * @author zhangzy
 * @date 2022/7/5
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = false)
public class LoginRequestResponse extends BaseMessage {
    private int code;
    private int descriptionLength;
    private String description;

    @Override
    public void encode(ByteBuf byteBuf) {
        byte[] descriptionBytes = description.getBytes(StandardCharsets.UTF_8);
        descriptionLength = descriptionBytes.length;

        byteBuf.writeInt(12 + 4 + 4 + descriptionLength);
        byteBuf.writeInt(0x80000001);
        byteBuf.writeInt(this.getSequence());
        byteBuf.writeInt(code);
        byteBuf.writeInt(descriptionLength);
        byteBuf.writeBytes(descriptionBytes);
    }

    @Override
    public BaseMessage decode(int length, int command, int sequence, ByteBuf body) {
        //初始化报文头
        this.setLength(length);
        this.setCommand(command);
        this.setSequence(sequence);
        //初始化包体属性
        this.code = body.readInt();
        this.descriptionLength = body.readInt();
        this.description = body.readCharSequence(descriptionLength, StandardCharsets.UTF_8).toString();
        return this;
    }
}
